package org.example.leetcpde;

public class mergeKLists
        implements IListNode {

    public ListNode mergeKLists(ListNode[] lists) {
        int length = lists.length;
        if (length == 0) {
            return null;
        }
        if (length == 1) {
            return lists[0];
        }
        return mergeKLists(lists, 0, length - 1);
    }

    public ListNode mergeKLists(ListNode[] lists,
                                int l,
                                int r) {
        if (l == r) {
            return lists[l];
        }

        int mid = (l + r) >> 1;
        ListNode l1 = mergeKLists(lists, l, mid);
        ListNode l2 = mergeKLists(lists, mid + 1, r);
        return mergeTwoLists(l1, l2);
    }

    ListNode mergeTwoLists(ListNode l1,
                           ListNode l2) {
        ListNode head = new ListNode(0), tail = head;
        while (l1 != null || l2 != null) {
            int v1 = l1 != null ? l1.val : Integer.MAX_VALUE;
            int v2 = l2 != null ? l2.val : Integer.MAX_VALUE;
            if (v1 <= v2) {
                tail.next = l1;
                l1 = l1.next;
            } else {
                tail.next = l2;
                l2 = l2.next;
            }
            tail = tail.next;
        }

        return head.next;
    }

}
